package adr

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"errors"
)

// 加密是公钥
const publicKey = `-----BEGIN PUBLIC KEY-----
MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgH6ozeOjvpsAy2VEtbrUbl0yiTaW
NT9CeZk5dVx/UwbAa/QFmR7bMQpRgxrcAyCZfEYtO8Scxx4dtbCr5FCevs0ktWzB
rww9HXkRRuSXQv+RCPH6wUvBFZ12n2b2OGAPy/dg55vgEjEyyjdORFJBeJZ4QOs4
zk4llJIYcPcn7VJNAgMBAAE=
-----END PUBLIC KEY-----`

const privateKey = `-----BEGIN RSA PRIVATE KEY-----
MIICWgIBAAKBgH6ozeOjvpsAy2VEtbrUbl0yiTaWNT9CeZk5dVx/UwbAa/QFmR7b
MQpRgxrcAyCZfEYtO8Scxx4dtbCr5FCevs0ktWzBrww9HXkRRuSXQv+RCPH6wUvB
FZ12n2b2OGAPy/dg55vgEjEyyjdORFJBeJZ4QOs4zk4llJIYcPcn7VJNAgMBAAEC
gYARwk9j/KCMETdzkoe8k26KCLzud28t2H8+Oa038+5LQw2f4G0Qw4EDxlwQlwql
NoATQuJfdfABS/8er2tK1oc//7xj7V3kDeNutDNMZmr23RvbNCitluRUTEACrVqo
deboeSqIgSLX3mhqn0Eg9v1azxjwV5yQxPfrinNHBk8CTQJBALu/nLduHqyikcMG
EvarcQgSWj1leJEJrTVTll2Z7C+/Q5g2n82befaB2Celyy/BLpSGTrRgbXVjjpvu
LPNlaWMCQQCstBLozK/Vh6ysAABMuZ74Uzdt6DAG9M9WRAQnXHV5tjdcn+Neu6rq
JS82yN4nhXzFgi8R/EGm5SNnJdZybvyPAkAxCsFGDObIU4LdvZVwh6Hz6M9XoEzZ
Hfz3pAjwFEfkxQJEHWiqzYUTRiGPYbhslfqz401lwpZ1Bnd29cUaIxBfAkAF9fkp
G9d90T7+eMmJ3GZGP+kL3BW8R7rYSWSzTxem6ckjY0lfva56gmoMxAYW6x6RWprx
TfmeHw6HwuCR9o61AkAOamgchoxAGU5M1TAV5m7TMXX73Jdy3VFarx74VkyGc8iW
29PP2UrnTakO4lP59KjuialfFvP3bpBJ5ILSCSY3
-----END RSA PRIVATE KEY-----`

// 加密
func RsaEncrypt(origData []byte) ([]byte, error) {
	//解密pem格式的公钥
	block, _ := pem.Decode([]byte(publicKey))
	if block == nil {
		return nil, errors.New("resources key error")
	}
	// 解析公钥
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	// 类型断言
	pub := pubInterface.(*rsa.PublicKey)
	//加密
	return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
}

// 解密
func RsaDecrypt(ciphertext []byte) ([]byte, error) {
	//解密
	block, _ := pem.Decode([]byte(privateKey))
	if block == nil {
		return nil, errors.New("private key error!")
	}
	//解析PKCS1格式的私钥
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	// 解密
	return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}

// 加密
func RsaEncryptString(origData string) string {
	encryptString, _ := RsaEncrypt([]byte(origData))
	return base64.StdEncoding.EncodeToString(encryptString)
}

// 解密
func RsaDEncryptString(origData string) string {
	bb, _ := base64.StdEncoding.DecodeString(origData)
	decryptString, _ := RsaDecrypt(bb)
	return string(decryptString)
}
